from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

from ui.Ui_device_editor_dialog import Ui_Dialog_device_editor
import time
from database.db import Database

class Device_editor_signal(QObject):
    device_widget_new_row = Signal(dict)



class Device_new_dialog(QDialog):
    
    
    def __init__(self, parent=None):
        super(Device_new_dialog, self).__init__(parent)
        self.ui = Ui_Dialog_device_editor()
        self.ui.setupUi(self)
        
        self.setWindowTitle('新建设备')
        self.setModal(True)  # 设置窗体为模态窗口，必须为True
        self.setWindowFlags(Qt.WindowCloseButtonHint)  # 设置窗体仅显示关闭按钮

        self.signal = Device_editor_signal()


        self.ui.pushButton_ok.clicked.connect(self.slot_save)


    def slot_show(self):
        self.ui.lineEdit_name.clear()
        self.ui.lineEdit_ip.clear()
        self.ui.lineEdit_port.clear()
        self.ui.lineEdit_user.clear()
        self.ui.lineEdit_password.clear()
        self.ui.lineEdit_position.clear()
        self.ui.lineEdit__supplier.clear()
        self.ui.lineEdit_model.clear()
        self.ui.textEdit_info.clear()
        self.ui.lineEdit_port.setText('22')
        self.ui.lineEdit_port.setValidator(QIntValidator(1,65535))
        self.show()

    def slot_save(self):
        data = {
            'name'  :self.ui.lineEdit_name.text(),
            'ip'    :self.ui.lineEdit_ip.text(),
            'port'  :self.ui.lineEdit_port.text(),
            'user'  :self.ui.lineEdit_user.text(),
            'password':self.ui.lineEdit_password.text(),
            'position':self.ui.lineEdit_position.text(),
            'supplier':self.ui.lineEdit__supplier.text(),
            'model' :self.ui.lineEdit_model.text(),
            'info':self.ui.textEdit_info.toPlainText()
        }

        # 数据库存储
        current_time = time.localtime()
        created_time = time.strftime('%Y-%m-%d_%H:%M:%S',current_time)
        db = Database()
        fields = [
            'name','supplier','model','position',
            'ip','port','user','password',
            'info','created_time','updated_time'
            ]
        values =(
            data['name'],data['supplier'],data['model'],data['position'],
            data['ip'],data['port'],data['user'],data['password'],
            data['info'],created_time,created_time
            )
        db.insert('devices',fields,values)

        data_list = db.select('sqlite_sequence',['seq'],"name='devices'")
        data['id'] = data_list[0][0]
        data['创建时间'] = created_time
        db.close_conn()


  
        self.signal.device_widget_new_row.emit(data)

